<template>
  <div>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-input v-model="searchModel.rolename" placeholder="角色名称" clearable></el-input>
          <el-button type="primary" round icon="el-icon-search" @click="getRoleList">查询</el-button>
        </el-col>
        <el-col :span="4" align="right">
          <el-button type="primary" round icon="el-icon-plus" @click="openEditForm(null)"></el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 结果列表 -->
    <el-card>
      <el-table :data="roleList" stripe style="width: 100%">
        <el-table-column label="#" width="180">
          <template slot-scope="scope">
            <!--    (pageNo-1) * pageSize + index + 1      -->
            {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="角色id" width="230">
        </el-table-column>
        <el-table-column prop="name" label="角色名称" width="230">
        </el-table-column>
        <el-table-column prop="level" label="角色权限">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.level === 'super'" type="warning">{{scope.row.level}}</el-tag>
            <el-tag v-else-if="scope.row.level === 'normal'" type="success">{{scope.row.level}}</el-tag>
            <el-tag v-else>{{scope.row.level}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button @click="openEditForm(scope.row.id)" type="primary" icon="el-icon-edit" circle size="mini"></el-button>
            <el-button @click="deleteRole(scope.row)" type="danger" icon="el-icon-delete" circle size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!--  角色编辑对话框  -->
    <el-dialog @close="clearForm" :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="roleForm" ref="roleFormRef" :rules="rules">
        <el-form-item label="角色名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="roleForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="角色权限" prop="level" :label-width="formLabelWidth">
          <template>
            <el-select v-model="roleForm.level" placeholder="请选择">
              <el-option
                v-for="item in levels"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>
          </template>
        </el-form-item>

        <el-form-item
          prop="menuIdList"
          label="权限设置"
          :label-width="formLabelWidth"
        >
          <el-tree
            ref="menuRef"
            :data="menuList"
            :props="menuProps"
            show-checkbox
            default-expand-all
            node-key="id"
            style="width:55%"
          ></el-tree>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>
import roleApi from '@/api/roleManage'
import menuApi from '@/api/menuManage'
export default {
  data() {
    return {
      menuList: [],
      menuProps: {
        children: 'children',
        label: 'title'
      },
      levels: [{
        value: 'super',
        label: '管理员'
      },{
        value: 'normal',
        label: '工作人员'
      }, {
        value: 'low',
        label: '普通用户'
      }],
      total: 0,
      title: "",
      dialogFormVisible: false,
      formLabelWidth: '130px',
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      roleList: [],
      roleForm: {

      },
      rules: {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
      },
    };
  },
  methods: {
    getAllMenu() {
      menuApi.getAllMenu().then( response => {
        this.menuList = response.data;
      })
    },
    deleteRole(role) {
      this.$confirm(`您确认删除角色 ${role.name} ?`, '是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        roleApi.deleteRoleById(role.id).then( response => {
          this.$message({
            type: 'success',
            message: response.message
          });
          this.getRoleList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    saveRole() {
      // 触发表单验证
      this.$refs.roleFormRef.validate((valid) => {
        if (valid) {
          let selected = this.$refs.menuRef.getCheckedKeys();
          let halfSelected = this.$refs.menuRef.getHalfCheckedKeys();
          this.roleForm.menuIdList = selected.concat(halfSelected);
          console.log(this.roleForm.menuIdList)
          // 提交后端
          roleApi.saveRole(this.roleForm).then( response => {
            // 成功提示
            this.$message({
              message: response.message,
              type: 'success'
            });
            // 关闭对话框
            this.dialogFormVisible = false;
            // 刷新表格
            this.getRoleList();
          });
        } else {
          return false;
        }
      });
    },
    clearForm() {
      this.roleForm = {};
      this.$refs.roleFormRef.clearValidate();
      this.$refs.menuRef.setCheckedKeys([]);
    },
    openEditForm(id) {
      if (id == null)  this.title = '新增角色';
      else {
        this.title = '修改角色';
        roleApi.getRoleById(id).then( response => {
          this.roleForm = response.data;
          this.$refs.menuRef.setCheckedKeys(response.data.menuIdList);
        });
      }
      this.dialogFormVisible = true;
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.getRoleList();
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getRoleList();
    },
    getRoleList() {
      roleApi.getRoleList(this.searchModel).then(response => {
        this.roleList = response.data.roleList;
        this.total = response.data.total;
      });
    }
  },
  created() {
    this.getRoleList();
    this.getAllMenu();
  }
};
</script>

<style>
#search .el-input {
  width: 200px;
  margin-right: 10px;
}
.el-dialog .el-input {
  width: 55%;
}
</style>
